package com.example.workrecord.util;

import javax.servlet.http.HttpServletRequest;
import java.net.*;
import java.security.NoSuchAlgorithmException;
import java.security.NoSuchProviderException;
import java.security.SecureRandom;
import java.util.Enumeration;
import java.util.Random;
import java.util.UUID;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @ClassName: Tools
 * @Description: Tools
 * @Author: Wei
 * @Date: 2018/7/30 11:58
 * @Version: 1.0
 */
public class Tools {

    private static Pattern regex = Pattern.compile("^(((13[0-9])|(15([0-3]|[5-9]))|(18[0,5-9]))\\d{8})|(0\\d{2}-\\d{8})|(0\\d{3}-\\d{7})$");

    /**
     * 获得内网IP
     *
     * @return 内网IP
     */
    public String getIntranetIp() throws UnknownHostException {
        return InetAddress.getLocalHost().getHostAddress();
    }

    /**
     * 获得外网IP
     *
     * @return 外网IP
     */
    public String getInternetIp() throws UnknownHostException, SocketException {
        String intranetIp = getIntranetIp();
        Enumeration<NetworkInterface> networks = NetworkInterface.getNetworkInterfaces();
        InetAddress ip = null;
        Enumeration<InetAddress> addrs;
        while (networks.hasMoreElements()) {
            addrs = networks.nextElement().getInetAddresses();
            while (addrs.hasMoreElements()) {
                ip = addrs.nextElement();
                if (ip instanceof Inet4Address
                        && ip.isSiteLocalAddress()
                        && !ip.getHostAddress().equals(intranetIp)) {
                    return ip.getHostAddress();
                }
            }
        }
        // 如果没有外网IP，就返回内网IP
        return intranetIp;
    }

    /**
     * 从Request对象中获得客户端IP，处理了HTTP代理服务器和Nginx的反向代理截取了ip
     *
     * @param request
     * @return ip
     */
    public static String getLocalIp(HttpServletRequest request) {
        String remoteAddr = request.getRemoteAddr();
        String forwarded = request.getHeader("X-Forwarded-For");
        String realIp = request.getHeader("X-Real-IP");

        String ip = null;
        if (realIp == null) {
            if (forwarded == null) {
                ip = remoteAddr;
            } else {
                ip = remoteAddr + "/" + forwarded.split(",")[0];
            }
        } else {
            if (realIp.equals(forwarded)) {
                ip = realIp;
            } else {
                if (forwarded != null) {
                    forwarded = forwarded.split(",")[0];
                }
                ip = realIp + "/" + forwarded;
            }
        }
        return ip;
    }

    /**
     * 获取32位UUID
     *
     * @return
     */
    public static String get32UUID() {
        return UUID.randomUUID().toString().trim().replaceAll("-", "");
    }

    /**
     * 获取16位UUID
     *
     * @return
     */
    public static String get16UUID() {
        int first = new Random(10).nextInt(8) + 1;
        int hashCodeV = UUID.randomUUID().toString().hashCode();
        if (hashCodeV < 0) {//有可能是负数
            hashCodeV = -hashCodeV;
        }
        // 0 代表前面补充0
        // 4 代表长度为4
        // d 代表参数为正数型
        return first + String.format("%015d", hashCodeV);
    }

    /**
     * 随机生成六位数验证码
     *
     * @return
     */
    public static int getRandomNum6() throws NoSuchAlgorithmException, NoSuchProviderException {
        Random random = SecureRandom.getInstance("SHA1PRNG", "SUN");
        return random.nextInt(900000) + 100000;//(Math.random()*(999999-100000)+100000)
    }

    /**
     * 随机生成三位数验证码
     *
     * @return
     */
    public static int getRandomNum3() throws NoSuchAlgorithmException, NoSuchProviderException {
        Random random = SecureRandom.getInstance("SHA1PRNG", "SUN");
        return random.nextInt(900) + 100;//(Math.random()*(999999-100000)+100000)
    }

    /**
     * 验证邮箱
     *
     * @param email
     * @return
     */
    public static boolean checkEmail(String email) {
        boolean flag = false;
        try {
            String check = "^([a-z0-9A-Z]+[-|_|\\.]?)+[a-z0-9A-Z]@([a-z0-9A-Z]+(-[a-z0-9A-Z]+)?\\.)+[a-zA-Z]{2,}$";
            Pattern regex = Pattern.compile(check);
            Matcher matcher = regex.matcher(email);
            flag = matcher.matches();
        } catch (Exception e) {
            flag = false;
        }
        return flag;
    }

    /**
     * 验证手机号码
     *
     * @param mobileNumber
     * @return
     */
    public static boolean checkMobileNumber(String mobileNumber) {
        boolean flag = false;
        try {
            Matcher matcher = regex.matcher(mobileNumber);
            flag = matcher.matches();
        } catch (Exception e) {
            flag = false;
        }
        return flag;
    }

    /**
     * 过滤字符串内html片段
     *
     * @param str
     * @return
     */
    public static String filterHtml(String str) {
        str = str.replaceAll("<br>", "_hh_");
        String regxpForHtml = "<([^>]*)>"; // 过滤所有以<开头以>结尾的标签
        Pattern pattern = Pattern.compile(regxpForHtml);
        Matcher matcher = pattern.matcher(str);
        StringBuffer sb = new StringBuffer();
        boolean result1 = matcher.find();
        while (result1) {
            matcher.appendReplacement(sb, "");
            result1 = matcher.find();
        }
        matcher.appendTail(sb);
        return sb.toString().replaceAll("_hh_", "<w:br/>").replaceAll("&nbsp;", " ");
    }

    /**
     * 产生一个随机的字符串
     *
     * @param length
     * @return
     */
    public static String randomString(int length) throws NoSuchAlgorithmException, NoSuchProviderException {
        String str = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
        Random random = SecureRandom.getInstance("SHA1PRNG", "SUN");
        StringBuffer buf = new StringBuffer();
        for (int i = 0; i < length; i++) {
            int num = random.nextInt(62);
            buf.append(str.charAt(num));
        }
        return buf.toString();
    }

}
